#pragma strict
import System.Collections.Generic;

////////////////////////////////////////////////////////////////////////////////////
///动态添加,去除材质.
////////////////////////////////////////////////////////////////////////////////////
class MaterialChangerMotor{
	// 是否 使用原始的材质.
	var isAddOriginalMats:boolean = true;
	// 需要改变材质的节点
	private var target:Transform; 
	// 要加入的材质组.
	private var mats:Material[];

	private var rs:Renderer[];
	private var dict:Dictionary.<Renderer,Material[]> = new Dictionary.<Renderer,Material[]>();
	
	/* 构造器.
		target :　执行材质增减的Transform.
		mats : Material[] ,材质数组.
		rendererType:Type ,渲染器类型.
	*/
	function MaterialChangerMotor(target:Transform,mats:Material[],rendererType:Type){
		this.target = target;
		this.mats = mats;
		SetupOriginalMaterials(rendererType);
	}
	/** 1 收集原始的材质. */
	function SetupOriginalMaterials(rendererType:Type){
		if(target){
			var comps:Component[] = target.GetComponentsInChildren(rendererType);
			rs = System.Array.ConvertAll(comps,function(comp:Component):Renderer{
				return comp as Renderer;
			});
			for(var r:Renderer in rs){
				dict[r] = r.sharedMaterials;
			}
		}else{
			Debug.Log("target不能为null!");
		}
	}
	/** 加入指定的材质组 */
	function AddMat(){
		var list:List.<Material> = new List.<Material>();
		for(var r:Renderer in rs){
			list.Clear();
			if(isAddOriginalMats)
				list.AddRange(r.sharedMaterials);
			list.AddRange(mats);
			r.sharedMaterials = list.ToArray();
		}
	}
	/** 去除指定的材质组  */
	function RemoveMat(){
		for(var r:Renderer in rs){
			r.sharedMaterials = dict[r];
		}
	}
	
}